import { Index } from "../../../dbserve";
import { rules } from "../../../utils/rules";
const list = {
  name: { type: /[\w\d\u4e00-\u9fa5]/, required: true, message: '名称由字母、数字或汉字组成' },
  roles: { type: Array, default: () => [] },
}
const edit = {
  ...list,
  id: { type: Number, required: true }
}
export default class Role extends Index {
  constructor() { super('roleGroup'); this._getcoll() }
  // 获取权限组列表
  async list(req?: any, res?: any) {
    try {
      const { page = 1, size = 0, ...query } = req.query;
      const data = await this._query({ page: { page, size }, query });
      res.success(data)
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 添加权限组
  async add(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, list);
      if (error) throw message;
      const { name, roles = [] } = data;
      const num = await this._count({ name });
      if (num) throw '名称已存在';
      const bool = await this._add({ name, roles });
      if (bool) res.success(bool, '添加成功');
      else throw '添加失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 修改权限组
  async edit(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, edit);
      if (error) throw message;
      const { id, ...items } = data;
      if (!(await this._count({ id: id - 0 }))) throw '组不存在';
      const bool = await this._edit({ id, ...items });
      if (bool) res.success(bool, '更新成功');
      else throw '更新失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 删除权限组
  async del(req?: any, res?: any) {
    try {
      const { id } = req.body;
      if (!id) throw 'id不能为空';
      const bool = await this._del(id);
      if (bool) res.success(bool, '删除成功');
      else throw '删除失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
}



